// miniprogram/pages/afterSaleDetail/afterSaleDetail.js
import {loadOneForAfterSales} from '../../api/api.js';
import {findMerchant} from '../../api/api.js';
import {updateForAfterSales,getAddressById} from '../../api/api.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
      afterSaleDetail:{},
      orderDetailsList:{},
      orderAfterSales:{},
      orderInfo:{},
      phone:"",
      show:false,
      express:"ems",
      expressNum:"",
      returnAddress:{}


  },


  confirmReceiveGood(){
    let that = this;
     let data = this.data.orderAfterSales;
     data.status = 4;
     data.autoexecDate = null;
     data.openId = wx.getStorageSync('loginInfo').openid,


    updateForAfterSales(data).then(res=>{
      console.log(res,"------");
      if(res.data.code == 200){
         setTimeout(() => {
           wx.showToast({
             title: '提交成功',
           })
         },1000);
         
         //关闭弹出框
          this.setData({
           show:false
          })
          that.onShow();
      }else{
          wx.showToast({
            title:res.data.msg,
            icon:'none'
          })
      }
    })   
  },


  //跳转到详情页面
  toDetail(e){
    let id = e.currentTarget.dataset.id;
    console.log(id);
    wx.navigateTo({
      url: '/pages/goodsDetails/goodsDetails?id='+id,
    })
  },


        // 点击填写单号
      inputLogisCode(){
          //  显示输入框
            this.setData({
                show:true
            })
      },

      // 发送售后信息
      sendMsg(){

        let that = this;
        let returnShippingName = this.data.express;
        let returnShippingCode = this.data.expressNum;

        // console.log(this.data.orderAfterSales);
        // return;

        // id
        // openId
        // status
        // version
        

        let data1 = {
          status:2,  
          returnShippingName,
          returnShippingCode,
          id:this.data.orderAfterSales.id,
          openId:wx.getStorageSync('loginInfo').openid,
          version:this.data.orderAfterSales.version,
          afterSalesType:this.data.orderAfterSales.afterSalesType,
        }


        console.log(data1,"----111111");


        updateForAfterSales(data1).then(res=>{
             console.log(res,"------");
             if(res.data.code == 200){
                setTimeout(() => {
                  wx.showToast({
                    title: '提交成功',
                  })
                },1000);
                
                //关闭弹出框
                 this.setData({
                  show:false
                 })
                 that.onShow();
             }else{
                 wx.showToast({
                   title:res.data.msg,
                   icon:'none'
                 })
             }
        })
      },

   /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    /**
     * openId,
     * orderId
     * **/ 
    let option = getCurrentPages()[getCurrentPages().length-1].options;
    console.log(option)
    //这个id 是售后id字段名就叫做id
    let data={
       openId:wx.getStorageSync('loginInfo').openid,
       id:option.id 
    }

    
    loadOneForAfterSales(data).then(res=>{
        console.log(res.data.data,"售后详情");
        if(res.data.data){
           wx.showToast({
             title: '订单不存在',
             icon:'none'
           })

        }
        let afterSaleDetail = res.data.data;
        let orderAfterSales = afterSaleDetail.orderAfterSales;
        let orderDetailsList = afterSaleDetail.orderDetailsList;
        let orderInfo = afterSaleDetail.orderInfo;
        //解析规格,然后保存到data中
        this.parseSpec(orderDetailsList);
        //解析时间格式，计算倒计时autoexecDate
        this.parseTime(orderAfterSales);
        // 
        // this.setData({
        //       afterSaleDetail:res.data.data
        // })
        //afterSaleDetail
        this.getPhone(orderInfo);

        //判断有没有 returnAddressid（退货地址）
        //如果有那么查询退货地址然后展示在页面上，如果没有那么不展示。
        if(this.data.orderAfterSales.returnAddressId){
          getAddressById(this.data.orderAfterSales.returnAddressId).then(res=>{
                console.log(res,"根据id 获取地址=============");
                this.setData({
                  returnAddress:res.data.data
                })
          })
        }



    })


  },



  //关闭弹出框
  onClose() {
    this.setData({ show: false });
  },




  

  onChange(event) {
    this.setData({
      express: event.detail
    });

    console.log(event.detail);
  },


  input(e){
       console.log(e.detail.value);
       this.setData({
         expressNum:e.detail.value
       })
  },

  





//获取商家电话号码
    getPhone(orderInfo){
        let merchantId = orderInfo.merchantId;
        console.log(merchantId,"电话号码")
        
        findMerchant(merchantId).then(res=>{
             console.log(res,"=========已经获取大电话号码");
             this.setData({ 
                 phone:res.data.data.phone,
                 merchantId:res.data.data.id,
             })
        })
    },

    //店家拨打电话按钮
    call(){

         console.log("拨打电话",this.data.phone);
         if(this.data.phone == null){
             wx.showToast({
               title:'店家没有添加手机号码哦',
               icon:"none"
             })
         }else{niahsdkzheh
           
            wx.makePhoneCall({
              phoneNumber:this.data.phone //仅为示例，并非真实的电话号码
            })
         }
    },



 


//  在线联系卖家
  contactSell(){
    //在线联系卖家
    console.log("根据一些信息，跳转到聊天窗口，然后连接聊天服务器");
    let id = this.data.merchantId;
    let time =new Date().getTime();
    wx.navigateTo({
       url:'/pages/chat/chat?merchantId='+id+'&time='+time,
    })

  },

   
  //客服介入
  CustomerServerIn(){
      console.log("客服介入");
       // status  处理状态 1等待买家处理/2等待卖家处理/3平台介入/4处理完成/5撤销售后
      //  if(this.data.orderAfterSales.status == 4|| this.data.orderAfterSales.status == 5){
      //     wx.showToast({
      //       title: '当前状态下客服无法介入',
      //       icon:'none'
      //     })

      //     return;
      // }

      let data = {
        openId:wx.getStorageSync('loginInfo').openid,
        id:this.data.orderAfterSales.id,
        version:this.data.orderAfterSales.version,
        status:3,
        afterSalesType:this.data.orderAfterSales.afterSalesType,

      }
      updateForAfterSales(data).then(res=>{
          console.log(res);
          if(res.data.code == 200){
            wx.showToast({
              title: '平台已经介入',
            })
          }else{
             wx.showToast({
               title: '服务器错误',
               icon:'none'
             })
          }
      })
  },

  // 撤销申请
   cancelApply(){
       console.log("撤销申请");
       let that  =this;
      //  let orderAfterSales = this.data.orderAfterSales;
      //  orderAfterSales.status = 5;
      //  console.log(orderAfterSales);
      // status  处理状态 1等待买家处理/2等待卖家处理/3平台介入/4处理完成/5撤销售后
       if(this.data.orderAfterSales.status == 4|| this.data.orderAfterSales.status == 5){
           wx.showToast({
             title: '当前状态下不可以撤销申请',
             icon:'none'
           })
           return;
       }

       let data = this.data.orderAfterSales;
       data.status = 5;
       data.openId = wx.getStorageSync('loginInfo').openid;
       data.autoexecDate = null;

      //  let data = {
      //      id:this.data.orderAfterSales.id,
      //      version:this.data.orderAfterSales.version,
      //      status:5,
      //  }

       

       updateForAfterSales(data).then(res=>{
           console.log(res);
           if(res.data.code == 200){
              wx.showToast({
                title: '撤销成功',
              })

              that.onShow();
           }else{
               wx.showToast({
                 title: '服务器错误',
                 icon:'none'
               })
           }
       })
   },

  //修改申请
  changeApply(){
       console.log("修改申请");
       let list = this.data.orderDetailsList
    //    wx.navigateTo({
    //      url:'/pages/applyForAfterSales/applyForAfterSales',
    //    })

       let id = this.data.orderAfterSales.id;
       console.log(id);

       let orderDetail = {
           details:list  
       }
       orderDetail = JSON.stringify(orderDetail);
       wx.navigateTo({
         url:'/pages/applyForAfterSales/applyForAfterSales?id='+id
       })
  },

  parseTime(orderAfterSales){
     let time = orderAfterSales.autoexecDate;
     if(time == null||time == undefined||time == ''){
         orderAfterSales.autoexecDate = "系统异常，无时间数据";
     }else{
                // 开始时间
            var begin = new Date();
            // 结束时间
            var end = new Date(time);
            //时间相差毫秒数
            var span = end.getTime() - begin.getTime();
            console.info(span);//36290000
            //计算相差天数
            var result = '';
            var days = Math.floor(span / (24 * 3600 * 1000));
            result += days + '天';
            //相差小时数
            var leave1 = span % (24 * 3600 * 1000);
            var hours = Math.floor(leave1 / (3600 * 1000))
            result += hours + '小时';
            //相差分钟
            var leave2 = leave1 % (3600 * 1000)
            var minutes = Math.floor(leave2 / (60 * 1000));
            result += minutes + '分钟';
            //相差秒
            var level3 = leave2 % (60 * 1000)
            var seconds = Math.round(level3 / 1000);
            result += seconds + '秒';
            console.info(result); //0天10小时4分钟50秒
            orderAfterSales.autoexecDate = result;
     }
     
      this.setData({
          orderAfterSales
      })
  },


//    解析规格
  parseSpec(orderDetailsList){
    // foreach 是对原来的数据进行修改
     orderDetailsList.forEach(item=>{
         item.specName = JSON.parse(item.specName);
     })
     this.setData({
        orderDetailsList:orderDetailsList
     })
  },

 
 
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})